import { makeAutoObservable, runInAction } from 'mobx';
import * as api from '../../api';

class CurrentUser {

  loading: boolean;
  userData: any;
  needChangePassword: boolean;

  constructor() {
    this.loading = false;
    this.userData = { id: '' };
    this.needChangePassword = false;
    makeAutoObservable(this);
  }

  async fetch() {
    if (this.loading) {
      return;
    }

    runInAction(() => {
      this.loading = true;
    });
    const res: any = await api.GET('/api/currentUser', null, null);
    const data: any = res.success ? res.data : {};
    if (data.needChangePassword) {
      this.setNeedChangePassword(true);
    }
    runInAction(() => {
      this.userData = data;
      this.loading = false;
    });
  }

  hasRole(role: string) {
    if (!this.userData || !this.userData?.id) {
      return false;
    }
    if (this.userData.superuser) {
      return true;
    }
    const authorities: any[] = this.userData.authorities || [];
    return this.containsRole(authorities, role);
  }

  containsRole(authorities: any[], role: string) {
    let flag: boolean = false;
    authorities.forEach((item: any) => {
      if (item.authority === role) {
        flag = true;
      }
    });
    return flag;
  }

  setUserData(userData: any) {
    runInAction(() => {
      this.userData = userData;
    });
  }

  setNeedChangePassword(needChangePassword: boolean) {
    runInAction(() => {
      this.needChangePassword = needChangePassword;
    });
  }

};

const currentUser = new CurrentUser();

export default currentUser;
